14. Exercise: Adapter Pattern
Exercise: Adapter Pattern
Remember that exercise last lesson, MergeShards.java
?
Your coworker, who is a design patterns whiz, was glancing over that code during a code review and noticed that it opens many files at once. In order to increase the cleanliness of the code, she suggests using the Adapter Pattern to simplify that code and manage the opening and closing of all the shard files.
Your starter code for this exercise is the solution code to MergeShards.java
, with the addition of a helper class, MultiFileReader.java
, that you need to fill in. MultiFileReader
implements the Closeable
interface. Recall that any object that implements Closeable
can be declared as a resource using the try-with-resources
idiom. Where does the adapter pattern fit in? In this case, you are adapting your List<Path>
of shard files to the Closeable
interface to make the readers easier to manage.
- First, implement the
MultiFileReader(List<Path> paths)
constructor, which should create a list ofBufferedReader
s from the givenpaths
. If any of theBufferedReader
s throws an exception, be sure to close the readers you've already created! - Next, implement the
MultiFileReader#close()
method, which should close all theBufferedReader
s. - When you are done implementing
MultiFileReader
, complete all theTODO
s inMergeShards.java
to use your new adapter! The newmain
method should look a lot cleaner!
Running the solution
Finally, if you want, you can rerun the shard merger to make sure it still works:
javac MergeShards.java
java MergeShards shards/ sorted.txt
TODO List
Task Feedback:
Nice work!
Code
If you need a code on the https://github.com/udacity.
export PATH=/data/jdk-15.0.1/bin:$PATH
export JAVA_HOME=/data/jdk-15.0.1/bin